package com.pro.xwt.rest.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.pro.xwt.common.example.BProjectExample;
import com.pro.xwt.common.example.RProjFlowExample;
import com.pro.xwt.common.model.BEmployee;
import com.pro.xwt.common.model.BLog;
import com.pro.xwt.common.model.BProject;
import com.pro.xwt.common.model.BTask;
import com.pro.xwt.common.model.DFile;
import com.pro.xwt.common.model.DFolder;
import com.pro.xwt.common.model.RProjEmp;
import com.pro.xwt.common.model.RProjEmpKey;
import com.pro.xwt.common.model.RProjFlow;
import com.pro.xwt.common.service.BEmployeeService;
import com.pro.xwt.common.service.BLogService;
import com.pro.xwt.common.service.BProjectService;
import com.pro.xwt.common.service.BTaskService;
import com.pro.xwt.common.service.BTemplateService;
import com.pro.xwt.common.service.DFileService;
import com.pro.xwt.common.service.DFolderService;
import com.pro.xwt.common.service.RProjEmpService;
import com.pro.xwt.common.service.RProjFlowService;
import com.pro.xwt.common.service.RTempFlowService;
import com.pro.xwt.rest.ResponseResult;

@Controller
@RequestMapping("/projects")
public class BProjectController {
	@Autowired
	BProjectService bProjectService;
	@Autowired
	BTemplateService bTemplateService;
	@Autowired
	RProjFlowService rProjFlowService;
	@Autowired
	RTempFlowService RTempFlowService;
	@Autowired
	RProjEmpService rProjEmpService;
	@Autowired
	BTaskService bTaskService;
	@Autowired
	BEmployeeService bEmployeeService;
	@Autowired
	DFileService dFileService;
	@Autowired
	DFolderService dFolderService;
	@Autowired
	BLogService bLogService;

	/**
	 * 添加项目接口
	 * 
	 * @param bProject
	 * @return
	 */
	@RequestMapping(method = { RequestMethod.POST }, value = "")
	@ResponseBody
	public ResponseResult add(@RequestBody BProjectExample bProjectExample, HttpServletRequest request) {
		if (bProjectExample.getStartTime().getTime() < bProjectExample.getEndTime().getTime()) {
			BEmployee user = (BEmployee) request.getAttribute("user");
			bProjectExample.setCreateEmpId(user.getId());
			int flag = bProjectService.insertProj(bProjectExample);
			BProject bP = bProjectService.findById(bProjectExample.getId());
			if (flag > 0) {
				return ResponseResult.success("添加项目成功", bP);
			} else {
				return ResponseResult.fail("添加项目失败", flag);
			}
		}
		return ResponseResult.fail("项目开始时间大于等于项目结束时间", bProjectExample);
	
	}

	/**
	 * 
	 * 项目人员绑定接口
	 * 
	 * @return
	 */
	@RequestMapping(method = { RequestMethod.POST }, value = "/{id}/employees")
	@ResponseBody
	public ResponseResult addProEmp(@PathVariable String id, @RequestBody RProjEmp rProjEmp,
			HttpServletRequest request) {
		if (!isOwnerOrAdmin((BEmployee) request.getAttribute("user"), id)) {
			return ResponseResult.fail("你没有该权限", false);
		}
		Integer flag = 0;
		Date date = new Date();
		BEmployee user = (BEmployee) request.getAttribute("user");
		if (id != null && rProjEmp != null && user != null) {
			rProjEmp.setProjId(id);
			rProjEmp.setCreateTime(date);
			rProjEmp.setCreateEmpId(user.getId());
			rProjEmp.setDeleteState("0");
			flag = rProjEmpService.insert(rProjEmp);
			if (flag > 0) {
				return ResponseResult.success("项目绑定成功", true);
			} else {
				return ResponseResult.fail("项目绑定失败", false);
			}
		} else {
			return ResponseResult.fail("传参错误", false);
		}

	}

	/**
	 * 任务查询接口
	 * 
	 * @param projId
	 * @param proFlowId
	 * @param empId
	 * @return
	 */
	@RequestMapping(method = { RequestMethod.GET }, value = "/{projId}/projFlows/{projFlowId}/tasks")
	@ResponseBody
	public ResponseResult getTask(@PathVariable String projId, @PathVariable String projFlowId) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (projId != null && projFlowId != null) {
			map.put("projId", projId);
			map.put("projFlowId", projFlowId);
			map.put("deleteState", "0");
			map.put("cycleTime", "NONE");
			// map.put("comState", "0");
			PageHelper.orderBy("com_state asc,last_end_time asc");
			
			List<BTask> list = bTaskService.queryListAll(map);
			return ResponseResult.success("任务获取成功", list);
		} else {
			return ResponseResult.fail("传参错误", null);
		}
	}

	/**
	 * 修改项目流程顺序接口
	 * 
	 * @param bProject
	 * @return
	 * @see 暂无此操作
	 */
	@RequestMapping(method = { RequestMethod.PUT }, value = "/{id}/projFlows")
	@ResponseBody
	public ResponseResult update(@PathVariable String id, @RequestBody Map<String, RProjFlowExample> map,
			HttpServletRequest request) {
		if (!isOwnerOrAdmin((BEmployee) request.getAttribute("user"), id)) {
			return ResponseResult.fail("你没有该权限", false);
		}
		List<RProjFlowExample> list = (List<RProjFlowExample>) map.get("data");
		int flag = rProjFlowService.updateProjectFlowList(id, list);
		if (flag > 0) {
			return ResponseResult.success("修改项目流程成功", flag);
		} else {
			return ResponseResult.fail("修改项目流程失败", flag);
		}
	}

	/**
	 * 修改项目流程名称
	 * 
	 * @param id
	 * @param rProjFlow
	 * @return
	 */
	@RequestMapping(method = { RequestMethod.PUT }, value = "/{projId}/projFlows/{id}")
	@ResponseBody
	public ResponseResult update(@PathVariable String id, @PathVariable String projId, @RequestBody RProjFlow rProjFlow,
			HttpServletRequest request) {
        if (!isOwnerOrAdmin((BEmployee) request.getAttribute("user"), projId)) {
			return ResponseResult.fail("你没有该权限", false);
		}
		rProjFlow.setId(id);
		Integer flag = 0;
		flag = rProjFlowService.update(rProjFlow);
		RProjFlow rp = rProjFlowService.findById(rProjFlow.getId());
		if (flag > 0) {
			return ResponseResult.success("修改项目流程名成功", rp);
		}
		return ResponseResult.fail("修改项目流程名失败", flag);

	}

	/**
	 * 项目人员查找接口
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(method = { RequestMethod.GET }, value = "/{id}/employees")
	@ResponseBody
	public ResponseResult getEmp(@PathVariable String id) {
		if (id != null) {
			List<BEmployee> list = bEmployeeService.selectEmployeeByProject(id);
			return ResponseResult.success("项目人员查找成功", list);
		} else {
			return ResponseResult.fail("传参错误", null);
		}
	}

	/**
	 * 项目人员移除接口
	 * 
	 * @param projId
	 * @param emp
	 * @return
	 */
	@RequestMapping(method = { RequestMethod.DELETE }, value = "/{projId}/employees/{empId}")
	@ResponseBody
	public ResponseResult getEmp(@PathVariable String projId, @PathVariable String empId, HttpServletRequest request) {
		if (!isOwnerOrAdmin((BEmployee) request.getAttribute("user"), projId)) {
			return ResponseResult.fail("你没有该权限", false);
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("createEmpId", empId);
		map.put("id", projId);
		bProjectService.findByCondition(map);
		if (bProjectService.findByCondition(map) != null) {
			return ResponseResult.fail("你不能删除自己", false);
		}
		RProjEmpKey rProjEmp = new RProjEmpKey();
		rProjEmp.setEmpId(empId);
		rProjEmp.setProjId(projId);
		// rProjEmp.setDeleteState("1");
		Integer flag = rProjEmpService.deleteByPrimaryKey(rProjEmp);
		if (flag > 0) {
			return ResponseResult.success("项目人员移除成功", flag);
		} else {
			return ResponseResult.fail("项目人员移除失败", flag);
		}
	}
	
	/**
	 * 根据项目id查找其项目流程接口
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(method = { RequestMethod.GET }, value = "/{id}/projFlows")
	@ResponseBody
	public ResponseResult getFlowByPId(@PathVariable String id) {
		PageHelper.orderBy("sort asc");
		List<RProjFlow> list = rProjFlowService.selectFlowByProject(id);
		return ResponseResult.success("获取资源成功", list);
	}

	/**
	 * 根据项目id查找文件夹文件接口
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(method = { RequestMethod.GET }, value = "/{id}/files")
	@ResponseBody
	public ResponseResult getFiles(@PathVariable String id) {
		Map<String, Object> map = new HashMap<>();
		List<DFile> dFiles = dFileService.findByProjId(id);
		List<DFolder> dFolders = dFolderService.findByProjId(id);
		map.put("file", dFiles);
		map.put("folder", dFolders);
		return ResponseResult.success("获取资源成功", map);
	}
	
	/**
	 * 删除项目
	 * @param proId
	 * @param request
	 * @return
	 */
	@RequestMapping(method = { RequestMethod.DELETE }, value = "{projId}")
	@ResponseBody
	public ResponseResult deleteProject(@PathVariable String projId, HttpServletRequest request) {
		if (!isOwnerOrAdmin((BEmployee) request.getAttribute("user"), projId)) {
			return ResponseResult.fail("你没有该权限", false);
		}
		Integer flag = bProjectService.deleteProjById(projId);
		if (flag >= 0) {
			return ResponseResult.success("删除项目及相关联数据成功", flag);
		}
		return ResponseResult.fail("删除项目失败", flag);
	}
	
	/**
	 * 修改项目
	 * @param proId
	 * @param request
	 * @return
	 */
	@RequestMapping(method = { RequestMethod.PATCH }, value = "{projId}")
	@ResponseBody
	public ResponseResult updateProject(@PathVariable String projId, HttpServletRequest request,@RequestBody BProjectExample bProjectExample) {
		if (!isOwnerOrAdmin((BEmployee) request.getAttribute("user"), projId)) {
			return ResponseResult.fail("你没有该权限", false);
		}
		System.out.println(bProjectExample.getSummary());
		bProjectExample.setId(projId);
		Integer flag = bProjectService.update(bProjectExample);
		if (flag > 0) {
			BProject bP = bProjectService.findById(projId);
			return ResponseResult.success("更新项目成功", bP);
		}
		return ResponseResult.fail("更新项目失败", flag);
	}
	
	/**
	 * 获取项目的已完成或未完成任务接口
	 * @param projId
	 * @param request
	 * @param bTask
	 * @return
	 */
	@RequestMapping(method = { RequestMethod.POST }, value = "{projId}")
	@ResponseBody
	public ResponseResult getProjectTasks(@PathVariable String projId, HttpServletRequest request,@RequestBody Map<String,Object> map) {
		int pageNo=Integer.parseInt(String.valueOf(map.get("pageNo")==null?1:map.get("pageNo")));
		int pageSize =Integer.parseInt(String.valueOf(map.get("pageSize")==null?10:map.get("pageSize")));
		int pageNum=pageNo*pageSize;
		PageHelper.startPage(pageNum, pageSize);
		PageHelper.orderBy("create_time desc");
		map.put("projId", projId);
		map.put("cycleTime","NONE");
		map.put("deleteState","0");
		List<BTask> bTasks=bTaskService.queryListAll(map);
		int tasksSum=bTaskService.count(map);
		int pageSum = tasksSum / pageSize;
		if(tasksSum%pageSize == 0){
			
		}else{
			pageSum+=1;
		}
		map.clear();
		map.put("pageSize",pageSize);
		map.put("pageSum", pageSum);
		map.put("pageNo",pageNo);
		map.put("taskLists",bTasks);
		map.put("tasksSum",tasksSum);
		return ResponseResult.success("获取任务成功", map);
	}
	
	
	/**
	 * 获取超时任务接口
	 * @param projId
	 * @param request
	 * @param bTask
	 * @return
	 */
	@RequestMapping(method = { RequestMethod.POST }, value = "{projId}/overTimeTasks")
	@ResponseBody
	public ResponseResult getProjectOverTasks(@PathVariable String projId, HttpServletRequest request,@RequestBody Map<String,Object> map) {
		int pageNo=Integer.parseInt(String.valueOf(map.get("pageNo")==null?1:map.get("pageNo")));
		int pageSize =Integer.parseInt(String.valueOf(map.get("pageSize")==null?10:map.get("pageSize")));
		int pageNum=pageNo*pageSize;
		System.out.println(pageNum);
		PageHelper.startPage(pageNum, pageSize);
		PageHelper.orderBy("create_time desc");
		map.put("projId", projId);
		map.put("comState", "0");
		map.put("cycleTime","NONE");
		map.put("deleteState","0");
		map.put("lastEndTime", new Date());
		List<BTask> bTasks=bTaskService.queryListAll(map);
		int overTimeTaskSum = bTaskService.count(map);
		int pageSum = overTimeTaskSum / pageSize;
		if(overTimeTaskSum%pageSize == 0){
			
		}else{
			pageSum+=1;
		}
		map.clear();
		map.put("pageSize",pageSize);
		map.put("pageSum", pageSum);
		map.put("pageNo",pageNo);
		map.put("taskLists",bTasks);
		map.put("overTimeTaskSum", overTimeTaskSum);
		return ResponseResult.success("获取任务成功", map);
	}
	
	/**
	 * 获取项目的日志接口
	 * @param projId
	 * @param request
	 * @param bTask
	 * @return
	 */
	@RequestMapping(method = { RequestMethod.POST }, value = "{projId}/logs")
	@ResponseBody
	public ResponseResult getLogs(@PathVariable String projId, HttpServletRequest request,@RequestBody Map<String,Object> map) {
		int pageNo=Integer.parseInt(String.valueOf(map.get("pageNo")==""?1:map.get("pageNo")));
		int pageSize =Integer.parseInt(String.valueOf(map.get("pageSize")==""?10:map.get("pageSize")));
		int pageNum=pageNo*pageSize;
		//PageHelper.startPage(pageNum, pageSize);
		map.put("begin",pageNum);
		map.put("size", pageSize);
		map.put("projId", projId);
		List<BLog> logLists=bLogService.selectLogByProjId(map);		
		map.put("deleteState","0");		
		int logsSum = bLogService.count(map);
		
		int pageSum = logsSum / pageSize;
		if(logsSum%pageSize == 0){
			
		}else{
			pageSum+=1;
		}
		map.clear();
		map.put("pageSize", pageSize);
		map.put("pageSum", pageSum);
		map.put("pageNo",pageNo);
		map.put("logLists",logLists);
		return ResponseResult.success("获取资源成功", map);
		
	}
	
	public boolean isOwnerOrAdmin(BEmployee bEmployee, String projId) {
		if (bEmployee.getRole().equals("ADMIN")) {
			return true;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("createEmpId", bEmployee.getId());
		map.put("id", projId);
		bProjectService.findByCondition(map);
		return (bProjectService.findByCondition(map) != null);
	}
	
	
	
	
	
}
